import type { LineSeriesOption } from 'echarts/charts'
import { LineChart } from 'echarts/charts'
import type {
  GridComponentOption,
  LegendComponentOption
} from 'echarts/components'
import { GridComponent, LegendComponent } from 'echarts/components'
import type { ComposeOption } from 'echarts/core'
import * as echarts from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { forwardRef, useEffect, useImperativeHandle, useRef } from 'react'

import { priceSwitchUnit } from '@/utils/compUtils'
import { roundToNearestMultiple } from '@/utils/echartsUtil'

type DataAnalysisChartOption = ComposeOption<
  LineSeriesOption | GridComponentOption | LegendComponentOption
>

export interface DataAnalysisProps {
  dataAnalysisList: any
  maxx: any
}

echarts.use([LineChart, GridComponent, LegendComponent, CanvasRenderer])

const SafeEduDataAnalysis = forwardRef<
  { resize: () => void },
  DataAnalysisProps
>((props, ref) => {
  const chartDomRef = useRef<HTMLDivElement>(null)
  const dataAnalysisChartRef = useRef<any>(null)

  // 视口改变 echarts  -resize
  useImperativeHandle(ref, () => ({
    resize: () => {
      if (dataAnalysisChartRef.current) {
        // console.log('--DriverChart自适应--');
        dataAnalysisChartRef.current.resize()
      }
    }
  }))

  const { dataAnalysisList, maxx } = props
  useEffect(() => {
    if (!chartDomRef.current) return
    const numberInterval = roundToNearestMultiple(maxx)
    // const xAxisData = dataAnalysisList.map((dataItem) => dataItem.date)
    const seriesList: LineSeriesOption[] = [
      {
        type: 'line',
        smooth: true,
        lineStyle: {
          width: 1
        },
        symbol: 'none', //折线上对应的data[i]点的标记样式
        data: dataAnalysisList.yvalue,
        // areaStyle: {  //cursor:'pointer'是由面积图引起的
        //   color: 'purple'
        // },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(246,110,44, 0.3)' // 100% 处的颜色
              },
              {
                offset: 1,
                color: 'rgba(246,110,44, 0)' //   0% 处的颜色
              }
            ],
            global: false // 缺省为 false
          }
        }
      }
    ]
    if (dataAnalysisChartRef.current) {
      // console.log('--dataAnalysisChartRef.current--存在--');
      dataAnalysisChartRef.current.setOption({
        xAxis: {
          data: dataAnalysisList.xvalue
        },
        yAxis: {
          minInterval: numberInterval == 5 ? 1 : Math.ceil(numberInterval / 5),
          max: numberInterval == 5 ? 5 : undefined,
          // max: numberInterval,
          // minInterval: Math.ceil(numberInterval / 5),
          axisLabel: {
            margin: 8,
            textStyle: {
              color: '#999',
              fontSize: '12px'
            },
            formatter: function (value: string | number) {
              // if (Number(value) % 1 != 0)
              //   return "" // 如果非整数，返回空，避免0.几的人/车
              // else
              return priceSwitchUnit(value)
            }
          }
        },
        series: seriesList
      })
    } else {
      const dataAnalysisChart = echarts.init(chartDomRef.current, null, {
        renderer: 'canvas',
        locale: 'ZH'
      })

      const dataAnalysisOptions: DataAnalysisChartOption = {
        color: ['#F66E2C'],
        grid: {
          //坐标系
          top: 24,
          right: 30,
          // left: 15,
          bottom: 48
          // left: 52
        },
        xAxis: {
          type: 'category',
          data: [dataAnalysisList.xvalue],
          axisTick: { show: false }, //刻度
          axisLine: {
            //轴线
            lineStyle: {
              color: '#404040'
            }
          },
          axisLabel: {
            fontSize: 12,
            color: '#999999'
          },
          boundaryGap: false
        },
        yAxis: {
          axisLabel: {
            margin: 8,
            formatter: function (value: string | number) {
              // if (Number(value) % 1 != 0)
              //   return "" // 如果非整数，返回空，避免0.几的人/车
              // else
              return priceSwitchUnit(value)
            }
          },
          minInterval: numberInterval == 5 ? 1 : Math.ceil(numberInterval / 5),
          max: numberInterval == 5 ? 5 : undefined,
          // minInterval: Math.ceil(numberInterval / 5),
          // max: numberInterval,
          type: 'value',

          // offset: -25,
          splitLine: {
            lineStyle: {
              // dashOffset: 10000,
              type: 'dashed',
              color: '#403E3D'
            }
          }
        },
        series: seriesList
      }
      dataAnalysisChart.setOption(dataAnalysisOptions)

      dataAnalysisChartRef.current = dataAnalysisChart
    }
  }, [maxx, dataAnalysisList])

  useEffect(() => {
    return () => {
      if (dataAnalysisChartRef.current) {
        dataAnalysisChartRef.current.dispose() //销毁实例
        dataAnalysisChartRef.current = null
      }
    }
  }, [])

  return (
    <div style={{ width: '398px', height: '199px' }} ref={chartDomRef}></div>
  )
})

export default SafeEduDataAnalysis
